//
//  HomeViewModel.m
//  HLZhiHuDaily
//
//  Created by 胡林 on 16/3/2.
//  Copyright © 2016年 胡林. All rights reserved.
//

#import "HomeViewModel.h"
#import "NSDateFormatter+letf.h"
#import "StoryModel.h"


@interface SectionViewModel : NSObject

@property(copy,nonatomic)NSString *sectionTitleText;
@property(strong,nonatomic)NSArray *sectionDataSource;

- (instancetype)initWithDictionary:(NSDictionary *)dic;

@end
@implementation SectionViewModel

-(instancetype)initWithDictionary:(NSDictionary *)dic{
    self = [super init];
    if (self) {
        self.sectionTitleText = [self stringConvertToSectionTitleText:dic   [@"date"]];
        NSArray * stories = dic[@"stories"];
        NSMutableArray * storyMod = [NSMutableArray new];
        for (NSDictionary * dict in stories) {
            StoryModel * model = [[StoryModel alloc] initWithDictionary:dict];
            [storyMod addObject:model];
        }self.sectionDataSource = storyMod;
    }return self;

}
//设置时间格式
- (NSString*)stringConvertToSectionTitleText:(NSString*)str{
    NSDateFormatter * formatter = [NSDateFormatter sharedInstance];
    [formatter setDateFormat:@"yyyyMMdd"];
    NSDate * date = [formatter dateFromString:str];
    formatter.locale = [NSLocale localeWithLocaleIdentifier:@"zh-CH"];
    [formatter setDateFormat:@"MM月dd日 EEEE"];
    NSString * sectionTitle = [formatter stringFromDate:date];
    return sectionTitle;

}
@end

@interface HomeViewModel ()
//已加载最靠前那一天的日期字符串
@property(copy,nonatomic)NSString *currentLoadDayStr;

@end
@implementation HomeViewModel
-(NSUInteger)numberOfSections{
    return self.daysDataList.count;
}
-(NSUInteger)numberOfRowsInSection:(NSUInteger)section{
    SectionViewModel * secNM = self.daysDataList[section];
    return secNM.sectionDataSource.count;
}
///分组组名的字体和颜色
-(NSAttributedString *)titleForSection:(NSInteger)section{
    SectionViewModel * secVM = self.daysDataList[section];
    return [[NSAttributedString alloc] initWithString:secVM.sectionTitleText attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:18],NSForegroundColorAttributeName:[UIColor whiteColor]}];
}
//故事在索引路径
-(StoryModel *)storyAtIndexPath:(NSIndexPath *)indexPath{
    SectionViewModel * secVM = self.daysDataList[indexPath.section];
    StoryModel * story = secVM.sectionDataSource[indexPath.row];
    return story;
}
///获取最新的新闻
-(void)getLatestStories{
    
    [RequestURL getRequestWithUrl:@"news/latest" parameters:nil success:^(id responseObject) {
         NSDictionary *jsonDic = (NSDictionary*)responseObject;
        self.currentLoadDayStr = responseObject[@"data"];
        SectionViewModel * secVM = [[SectionViewModel alloc] initWithDictionary:jsonDic];
        _daysDataList = [NSMutableArray arrayWithObject:secVM];
        _storiesID = [NSMutableArray arrayWithArray:[secVM valueForKeyPath:@"sectionDataSource.storyID"]];
        
        NSArray * stories = jsonDic[@"top_stories"];
        NSMutableArray * storyModelList = [NSMutableArray new];
        for (NSDictionary * storydic in stories) {
            StoryModel * model = [[StoryModel alloc] initWithDictionary:storydic];
            [storyModelList addObject:model];
        }
        StoryModel * first = [storyModelList firstObject];
        StoryModel * last = [storyModelList lastObject];
        [storyModelList addObject:first];
        [storyModelList insertObject:last atIndex:0];
        [self setValue:storyModelList forKey:@"top_stories"];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"LoadLatestDaily" object:nil];
    } failure:nil];
    
    
}
//最新日期的故事
-(void)updateLatestStories{
        _isLoading = YES;
    [RequestURL getRequestWithUrl:@"news/latest" parameters:nil success:^(id responseObject) {
        NSDictionary * jsom = (NSDictionary *)responseObject;
        NSArray * stor = jsom[@"top_stories"];
        NSMutableArray *storyModels = [NSMutableArray new];
        for (NSDictionary * stoDic in stor) {
            StoryModel * model = [[StoryModel alloc] initWithDictionary:stoDic];
            [storyModels addObject:model];
        }
        StoryModel *first = [storyModels firstObject];
        StoryModel *last = [storyModels lastObject];
        [storyModels addObject:first];
        [storyModels insertObject:last atIndex:0];
        [self setValue:storyModels forKey:@"top_stories"];
        
        SectionViewModel *newvm = [[SectionViewModel alloc] initWithDictionary:jsom];
        SectionViewModel *oldvm = _daysDataList[0];
        
        if ([newvm.sectionTitleText isEqualToString:oldvm.sectionTitleText]) {
            NSArray* new = newvm.sectionDataSource;
            NSArray* old = oldvm.sectionDataSource;
            if (new.count>old.count) {
                NSUInteger newItemsCount = new.count-old.count;
                for (int i = 1; i <=newItemsCount; i++) {
                    StoryModel *model = new[newItemsCount-i];
                    [_storiesID insertObject:model.storyID atIndex:0];
                }
                [_daysDataList removeObject:oldvm];
                [_daysDataList insertObject:newvm atIndex:0];
            }
            [[NSNotificationCenter defaultCenter]postNotificationName:@"UpdateLatestDaily" object:nil];
        }else {
            _currentLoadDayStr = responseObject[@"date"];
            _daysDataList = [NSMutableArray arrayWithObject:newvm];
            _storiesID = [NSMutableArray arrayWithArray:[newvm valueForKeyPath:@"sectionDataSource.storyID"]];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"UpdateLatestDaily" object:nil userInfo:@{@"isNewDay":@(YES)}];
        }
        _isLoading = NO;
    } failure:nil];
    
}

- (void)getPreviousStories {
    _isLoading = YES;
    [RequestURL getRequestWithUrl:[NSString stringWithFormat:@"news/before/%@",_currentLoadDayStr] parameters:nil success:^(id responseObject) {
        NSDictionary *jsonDic = (NSDictionary*)responseObject;
        self.currentLoadDayStr = responseObject[@"date"];
        SectionViewModel *vm = [[SectionViewModel alloc] initWithDictionary:jsonDic];
        [_daysDataList addObject:vm];
        [_storiesID addObjectsFromArray:[vm valueForKeyPath:@"sectionDataSource.storyID"]];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"LoadPreviousDaily" object:nil];
        _isLoading = NO;
  
    } failure:nil];
}




@end






















